# -*- coding: utf-8 -*-
from gevent import monkey

monkey.patch_all(Event=True, subprocess=True)
from gevent.pywsgi import WSGIServer
from flask import *
import os
import logging
from logging.handlers import RotatingFileHandler
from api import api
from api import static
from admin import admin

try:
    import setting
except ImportError:
    import sys

    sys.path.append('..')
    import setting

app = Flask(__name__)

app.secret_key = os.urandom(24)

app.register_blueprint(api, url_prefix='/api')
app.register_blueprint(static, url_prefix='/static')
app.register_blueprint(admin, url_prefix='/admin')

app.config['DEBUG'] = setting.app['debug']
app.config['SESSION_COOKIE_NAME'] = setting.app['name']
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = setting.app['debug']

logger = logging.getLogger('web')
logfile = setting.app['logfile']
File_logging = RotatingFileHandler(logfile, maxBytes=5 * 1024 * 1024, backupCount=50)
File_logging.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(funcName)s %(message)s'))
File_logging.setLevel(setting.app['loglevel'])
logger.addHandler(File_logging)
logger.setLevel(setting.app['loglevel'])

if __name__ == '__main__':
    # app.run(host="0.0.0.0", port=setting.app['port'])
    server = WSGIServer(('', setting.app['port']), app, log=None, backlog=100000)
    server.serve_forever()
    # server.init_socket()
    # def serve_forever():
    #     try:
    #         server.start()
    #         try:
    #             server._stop_event.wait()
    #         except:
    #             raise
    #     except KeyboardInterrupt:
    #         pass
    # for i in xrange(setting.app['worker']-1):
    #     Process(target=serve_forever, args=tuple()).start()
    # serve_forever()
